<template>
  <div class="admin-management">
    <div class="admin-header">
      <h2>🔐 系统权限管理</h2>
      <p>RBAC权限管理系统 - 基于角色的访问控制</p>
    </div>

    <div class="admin-tabs">
      <button
        v-for="tab in tabs"
        :key="tab.id"
        :class="['tab-btn', { active: activeTab === tab.id }]"
        @click="activeTab = tab.id"
      >
        {{ tab.name }}
      </button>
    </div>

    <!-- 用户管理 -->
    <div v-if="activeTab === 'users'" class="tab-content">
      <div class="section-header">
        <h3>👥 用户管理</h3>
        <button class="btn-primary" @click="showUserDialog = true">
          + 添加用户
        </button>
      </div>

      <div class="user-grid">
        <div v-for="user in users" :key="user.id" class="user-card">
          <div class="user-avatar">
            {{ user.nickname.charAt(0) }}
          </div>
          <div class="user-info">
            <h4>{{ user.nickname }}</h4>
            <p class="username">@{{ user.username }}</p>
            <div class="user-meta">
              <span class="role-badge" :class="user.role">
                {{ getRoleName(user.role) }}
              </span>
              <span class="status" :class="user.status === '0' ? 'active' : 'inactive'">
                {{ user.status === '0' ? '正常' : '禁用' }}
              </span>
            </div>
          </div>
          <div class="user-actions">
            <button class="btn-sm" @click="editUser(user)">编辑</button>
            <button class="btn-sm btn-danger" @click="deleteUser(user)">删除</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 角色权限管理 -->
    <div v-if="activeTab === 'roles'" class="tab-content">
      <div class="section-header">
        <h3>🎭 角色权限管理</h3>
      </div>

      <div class="roles-container">
        <div class="role-sidebar">
          <div
            v-for="role in roles"
            :key="role.id"
            :class="['role-item', { active: selectedRole?.id === role.id }]"
            @click="selectRole(role)"
          >
            <div class="role-icon">🎯</div>
            <div class="role-details">
              <h4>{{ role.name }}</h4>
              <p>{{ role.description }}</p>
            </div>
          </div>
        </div>

        <div class="permission-panel" v-if="selectedRole">
          <div class="panel-header">
            <h3>{{ selectedRole.name }} - 权限配置</h3>
            <button class="btn-primary" @click="saveRolePermissions">
              保存权限
            </button>
          </div>

          <div class="permission-categories">
            <div v-for="category in permissionCategories" :key="category" class="category">
              <h4>{{ category }}</h4>
              <div class="permission-list">
                <label
                  v-for="perm in getPermissionsByCategory(category)"
                  :key="perm.code"
                  class="permission-item"
                >
                  <input
                    type="checkbox"
                    :value="perm.code"
                    v-model="selectedPermissions"
                    class="perm-checkbox"
                  >
                  <span class="checkmark"></span>
                  <span class="perm-name">{{ perm.name }}</span>
                  <span class="perm-code">{{ perm.code }}</span>
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户角色分配 -->
    <div v-if="activeTab === 'assign'" class="tab-content">
      <div class="section-header">
        <h3>🔗 用户角色分配</h3>
      </div>

      <div class="assignment-grid">
        <div class="user-list">
          <h4>用户列表</h4>
          <div
            v-for="user in users"
            :key="user.id"
            :class="['assignment-user', { active: selectedAssignUser?.id === user.id }]"
            @click="selectAssignUser(user)"
          >
            {{ user.nickname }}
            <span class="current-role">({{ getRoleName(user.role) }})</span>
          </div>
        </div>

        <div class="role-assignment" v-if="selectedAssignUser">
          <h4>为 {{ selectedAssignUser.nickname }} 分配角色</h4>
          <div class="role-options">
            <label
              v-for="role in roles"
              :key="role.id"
              class="role-option"
            >
              <input
                type="radio"
                :value="role.key"
                v-model="selectedUserRole"
                name="userRole"
              >
              <span class="radio-checkmark"></span>
              <div class="role-info">
                <strong>{{ role.name }}</strong>
                <p>{{ role.description }}</p>
              </div>
            </label>
          </div>
          <button class="btn-primary" @click="saveUserRole">
            保存角色分配
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { childEnglishApi } from '@/api/childEnglishApi';

export default {
  name: 'AdminManagement',
  data() {
    return {
      activeTab: 'users',
      tabs: [
        { id: 'users', name: '用户管理' },
        { id: 'roles', name: '角色权限' },
        { id: 'assign', name: '角色分配' }
      ],
      users: [],
      roles: [],
      permissions: [],
      selectedRole: null,
      selectedPermissions: [],
      selectedAssignUser: null,
      selectedUserRole: '',
      showUserDialog: false
    };
  },
  computed: {
    permissionCategories() {
      const categories = new Set();
      this.permissions.forEach(perm => {
        categories.add(perm.category);
      });
      return Array.from(categories);
    }
  },
  async mounted() {
    await this.loadAdminData();
  },
  methods: {
    async loadAdminData() {
      try {
        const response = await childEnglishApi.getAdminData();
        if (response.code === 200) {
          this.users = response.data.users;
          this.roles = response.data.roles;
          this.permissions = response.data.permissions;
        }
      } catch (error) {
        console.error('加载管理数据失败:', error);
        // 使用模拟数据
        this.loadMockData();
      }
    },

    loadMockData() {
      this.users = [
        { id: 1, username: 'admin', nickname: '管理员', role: 'admin', status: '0' },
        { id: 2, username: 'parent_zhang', nickname: '张爸爸', role: 'parent', status: '0' },
        { id: 3, username: 'child_xiaoming', nickname: '小明', role: 'child', status: '0' },
        { id: 4, username: 'teacher_li', nickname: '李老师', role: 'teacher', status: '0' }
      ];

      this.roles = [
        { id: 1, name: '超级管理员', key: 'admin', description: '拥有所有权限' },
        { id: 2, name: '家长', key: 'parent', description: '查看孩子学习进度' },
        { id: 3, name: '幼儿', key: 'child', description: '学习功能权限' },
        { id: 4, name: '教师', key: 'teacher', description: '教学管理权限' }
      ];

      this.permissions = [
        { code: 'system:user:view', name: '查看用户', category: '系统管理' },
        { code: 'system:user:edit', name: '编辑用户', category: '系统管理' },
        { code: 'system:user:delete', name: '删除用户', category: '系统管理' },
        { code: 'system:role:view', name: '查看角色', category: '系统管理' },
        { code: 'system:role:edit', name: '编辑角色', category: '系统管理' },
        { code: 'system:role:delete', name: '删除角色', category: '系统管理' },
        { code: 'system:permission:view', name: '查看权限', category: '系统管理' },
        { code: 'system:permission:edit', name: '编辑权限', category: '系统管理' },
        { code: 'learning:listening:view', name: '听力学习', category: '学习功能' },
        { code: 'learning:reading:view', name: '绘本阅读', category: '学习功能' },
        { code: 'learning:game:view', name: '游戏学习', category: '学习功能' },
        { code: 'parent:child:view', name: '查看孩子', category: '家长功能' },
        { code: 'parent:progress:view', name: '查看进度', category: '家长功能' },
        { code: 'parent:plan:edit', name: '编辑计划', category: '家长功能' },
        { code: 'teaching:class:view', name: '查看班级', category: '教师功能' },
        { code: 'teaching:content:edit', name: '编辑内容', category: '教师功能' },
        { code: 'teaching:report:view', name: '查看报告', category: '教师功能' }
      ];
    },

    getRoleName(roleKey) {
      const roleMap = {
        'admin': '管理员',
        'parent': '家长',
        'child': '幼儿',
        'teacher': '教师'
      };
      return roleMap[roleKey] || roleKey;
    },

    selectRole(role) {
      this.selectedRole = role;
      // 模拟加载角色权限
      this.selectedPermissions = this.getDefaultPermissions(role.key);
    },

    getDefaultPermissions(roleKey) {
      const permissionMap = {
        'admin': ['system:user:view', 'system:user:edit', 'system:user:delete', 'system:role:view', 'system:role:edit', 'system:role:delete', 'system:permission:view', 'system:permission:edit'],
        'parent': ['parent:child:view', 'parent:progress:view', 'parent:plan:edit'],
        'child': ['learning:listening:view', 'learning:reading:view', 'learning:game:view'],
        'teacher': ['teaching:class:view', 'teaching:content:edit', 'teaching:report:view']
      };
      return permissionMap[roleKey] || [];
    },

    getPermissionsByCategory(category) {
      return this.permissions.filter(perm => perm.category === category);
    },

    selectAssignUser(user) {
      this.selectedAssignUser = user;
      this.selectedUserRole = user.role;
    },

    async saveRolePermissions() {
      if (!this.selectedRole) return;

      try {
        const response = await childEnglishApi.updateRolePermissions({
          roleId: this.selectedRole.id,
          permissions: this.selectedPermissions
        });

        if (response.code === 200) {
          alert('权限更新成功！');
        }
      } catch (error) {
        alert('权限更新失败: ' + error.message);
      }
    },

    async saveUserRole() {
      if (!this.selectedAssignUser) return;

      try {
        const response = await childEnglishApi.updateUserRole({
          userId: this.selectedAssignUser.id,
          roleId: this.roles.find(r => r.key === this.selectedUserRole)?.id
        });

        if (response.code === 200) {
          alert('角色分配成功！');
          // 更新本地数据
          this.selectedAssignUser.role = this.selectedUserRole;
        }
      } catch (error) {
        alert('角色分配失败: ' + error.message);
      }
    },

    editUser(user) {
      alert(`编辑用户: ${user.nickname}`);
    },

    deleteUser(user) {
      if (confirm(`确定要删除用户 ${user.nickname} 吗？`)) {
        alert(`用户 ${user.nickname} 已删除`);
      }
    }
  }
};
</script>

<style scoped>
.admin-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.admin-header {
  text-align: center;
  margin-bottom: 30px;
  background: white;
  padding: 30px;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.admin-header h2 {
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 2em;
}

.admin-header p {
  color: #7f8c8d;
  font-size: 1.1em;
}

.admin-tabs {
  display: flex;
  background: white;
  border-radius: 10px;
  padding: 5px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.tab-btn {
  flex: 1;
  padding: 15px;
  border: none;
  background: none;
  cursor: pointer;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.tab-btn.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.tab-content {
  background: white;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 5px 20px rgba(0,0,0,0.1);
  min-height: 500px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 2px solid #ecf0f1;
}

.section-header h3 {
  color: #2c3e50;
  margin: 0;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

/* 用户网格样式 */
.user-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.user-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 10px;
  border-left: 4px solid #667eea;
  transition: all 0.3s ease;
}

.user-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 18px;
  margin-right: 15px;
}

.user-info h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.username {
  color: #7f8c8d;
  margin: 0 0 10px 0;
  font-size: 14px;
}

.user-meta {
  display: flex;
  gap: 10px;
}

.role-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.role-badge.admin { background: #e74c3c; color: white; }
.role-badge.parent { background: #3498db; color: white; }
.role-badge.child { background: #9b59b6; color: white; }
.role-badge.teacher { background: #2ecc71; color: white; }

.status {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.status.active { background: #d4edda; color: #155724; }
.status.inactive { background: #f8d7da; color: #721c24; }

.user-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.btn-sm {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s ease;
}

.btn-sm:hover {
  background: #f8f9fa;
}

.btn-danger {
  border-color: #e74c3c;
  color: #e74c3c;
}

.btn-danger:hover {
  background: #e74c3c;
  color: white;
}

/* 角色权限样式 */
.roles-container {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 30px;
}

.role-sidebar {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 20px;
}

.role-item {
  display: flex;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.role-item:hover {
  background: white;
  border-color: #667eea;
}

.role-item.active {
  background: white;
  border-color: #667eea;
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.2);
}

.role-icon {
  font-size: 24px;
  margin-right: 15px;
}

.role-details h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.role-details p {
  margin: 0;
  color: #7f8c8d;
  font-size: 12px;
}

.permission-panel {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 20px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ddd;
}

.permission-categories {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.category {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.category h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  padding-bottom: 10px;
  border-bottom: 1px solid #ecf0f1;
}

.permission-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 10px;
}

.permission-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.permission-item:hover {
  background: #e9ecef;
}

.perm-checkbox {
  margin-right: 10px;
}

.perm-name {
  font-weight: bold;
  color: #2c3e50;
  margin-right: 10px;
}

.perm-code {
  font-size: 12px;
  color: #7f8c8d;
  margin-left: auto;
}

/* 角色分配样式 */
.assignment-grid {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 30px;
}

.user-list, .role-assignment {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 20px;
}

.assignment-user {
  padding: 15px;
  margin-bottom: 10px;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.assignment-user:hover {
  border-color: #667eea;
}

.assignment-user.active {
  border-color: #667eea;
  background: #e3f2fd;
}

.current-role {
  color: #7f8c8d;
  font-size: 12px;
}

.role-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin: 20px 0;
}

.role-option {
  display: flex;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.role-option:hover {
  border-color: #667eea;
}

.role-option input[type="radio"] {
  margin-right: 15px;
}

.role-info {
  flex: 1;
}

.role-info strong {
  color: #2c3e50;
  display: block;
  margin-bottom: 5px;
}

.role-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .roles-container,
  .assignment-grid {
    grid-template-columns: 1fr;
  }

  .user-grid {
    grid-template-columns: 1fr;
  }

  .admin-tabs {
    flex-direction: column;
  }
}
</style>
